package cc.autoapi.pucong.auto.flow.persistence.repository.api;


import cc.autoapi.pucong.auto.flow.core.root.entity.UserJwt;
import cc.autoapi.pucong.auto.flow.core.root.utils.ApplicationContextUtil;
import cc.autoapi.pucong.auto.flow.core.root.utils.SystemConstant;
import cc.autoapi.pucong.auto.flow.persistence.bo.jwt.CheckResult;
import cc.autoapi.pucong.auto.flow.persistence.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @description:
 * @author: cong.pu
 * @create: 2024-11-04 15:13
 **/
public class AutoFlowAuthInterceptorDefault implements AutoFlowAuthInterceptor {

    private String usernameSelf;

    private String passwordSelf;

    public AutoFlowAuthInterceptorDefault(String username, String password) {
        this.usernameSelf = username;
        this.passwordSelf = password;
    }

    @Override
    public Boolean checkLogin(String userName, String password) {
        return usernameSelf.equals(userName) && passwordSelf.equals(password);
    }

    @Override
    public Boolean isLogin(HttpServletRequest request) {
        String user_token = JwtUtils.getToken();
        if (StringUtils.isNotBlank(user_token)) {
            // 校验token
            CheckResult checkResult = JwtUtils.verifyToken(user_token);
            if (checkResult.isSuccess()) {
                // 获取用户信息
                UserJwt loginUser = checkResult.getClaims().getUserJwt();
                if (loginUser == null) {
                    return false;
                }
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    @Override
    public UserJwt getLoginUser(HttpServletRequest request) {
        Object attribute = request.getAttribute(SystemConstant.JWT_TOKEN);
        if (attribute == null) {
            if (!ApplicationContextUtil.isDev()) {
                return null;
            } else {
                UserJwt userJwt = new UserJwt();
                userJwt.setUuid("1");
                userJwt.setUserName("超级管理员");
                userJwt.setLoginName("superadmin");
                return userJwt;
            }
        } else {
            UserJwt loginUser = (UserJwt) attribute;
            return loginUser;
        }
    }

    @Override
    public void loginOut(HttpServletRequest request) {
        request.removeAttribute(SystemConstant.JWT_TOKEN);
    }
}
